package com.atguigu.day03;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class Flink02_Transform_Filter {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.使用FlatMap获取到每一个单词
        SingleOutputStreamOperator<String> wordDStream = streamSource.flatMap(new FlatMapFunction<String, String>() {
            /**
             *
             * @param value 上游的数据
             * @param out 采集器，主要用来将数据发送给下游
             * @throws Exception
             */
            @Override
            public void flatMap(String value, Collector<String> out) throws Exception {
                String[] words = value.split(" ");
                for (String word : words) {
                    out.collect(word);
                }
            }
        });

        //TODO 4.使用Filter过滤出hello这个单词
        SingleOutputStreamOperator<String> filter = wordDStream.filter(new FilterFunction<String>() {
            /**
             *
             * @param value 上游发送过来的数据
             * @return
             * @throws Exception
             */
            @Override
            public boolean filter(String value) throws Exception {
                return "hello".equals(value);
            }
        });

        filter.print();

        env.execute();

    }
}
